var express = require('express');
var router = express.Router();
var mongo = require("./db")
var mongodb = require("mongodb")
var ObjectId = mongodb.ObjectId;

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});

// 添加接口
router.post("/add", function(req, res) {
        var obj = {
            pname: req.body.pname,
            price: req.body.price,
            oldPrice: req.body.oldPrice,
            inventory: req.body.inventory,
            sel: req.body.sel,
            song: req.body.song,
            pdes: req.body.pdes, //商品性质
            isRed: req.body.isRed
        }
        if (req.body.action == "add") {
            mongo("add", "plist", obj, function() {
                res.send({ success: "添加成功" })
            })
        } else if (req.body.action == "edit") {
            mongo("update", "plist", [{ _id: ObjectId(req.body.id) }, obj], function() {
                res.send({ success: "修改成功" })
            })
        }

    })
    // 查询所有商品的接口
router.post("/list", function(req, res) {
        // req.body.page 当前页码       2
        // req.body.pageSize 一页的条数  3
        var obj = {}
        if (req.body.sel) {
            obj.sel = req.body.sel;
        }
        mongo("find", "plist", obj, function(data) {
            res.send({ data: data.slice(req.body.pageSize * req.body.page - req.body.pageSize, req.body.pageSize * req.body.page), total: data.length })
        })
    })
    // 删除
router.post("/del", function(req, res) {
    mongo("del", "plist", { _id: ObjectId(req.body.id) }, function() {
        res.send({ success: "删除成功" })
    })
})
module.exports = router;